package vboot.core.framework.webservice;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.xml.ws.Endpoint;

@Component
@Slf4j
public class StartClas implements ApplicationRunner {

//    @Bean(name = Bus.DEFAULT_BUS_ID)
//    public SpringBus springBus() {
//        return new SpringBus();
//    }

    @Autowired
    private WebApplicationContext applicationConnect;

    @Autowired()
    @Qualifier(Bus.DEFAULT_BUS_ID)
    private SpringBus bus;

    @Bean(name = "wsBean")
    public ServletRegistrationBean dispatcherServlet() {
        ServletRegistrationBean wbsServlet = new ServletRegistrationBean(new CXFServlet(), "/wsv/*");
        return wbsServlet;
    }

//    @Bean
//    public PigService pigService() {
//        return new PigServiceImpl();
//    }




    @SuppressWarnings("resource")
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("开始进行自动发布webService接口");
//
        String[] beanNames = applicationConnect.getBeanNamesForAnnotation(AutoPublish.class);
        for(String beanName : beanNames) {
            String publishAddr = applicationConnect.getType(beanName).getAnnotation(AutoPublish.class).publishAddress();
            EndpointImpl endpoint = new EndpointImpl(bus, applicationConnect.getBean(beanName));
            endpoint.publish(publishAddr);
            log.info(String.format("发布接口地址：[%s]", "http://localhost:5000"+publishAddr));
        }

        log.info("weBservice接口自动发布结束");
//        EndpointImpl endpoint = new EndpointImpl(bus,pigService);
//        endpoint.publish("/api");
//        System.out.println("服务发布成功！地址为：http://localhost:8081/wsv/api?wsdl");
    }

    @Autowired
    private PigService pigService;

//
//    @Bean
//    public Endpoint endpointPurchase(SpringBus springBus) {
//
//
//
//        return endpoint;
//
//    }
}